const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

exports.main = async (event) => {
  try {
    const db = cloud.database();
    const { page, pageSize, name, phone } = event;
    
    // 构建动态查询条件--存储搜索条件
    const queryCondition = {};
    
    // 名称模糊搜索（不区分大小写）
    if (name && name.trim()) {
      // 1. 创建正则表达式对象
      const nameRegExp = db.RegExp({
        regexp: name, 
        options: 'i' // 不区分大小写
      });
    
      // 2. 设置复合查询条件
      queryCondition.$or = [
        { nickName: nameRegExp },
        { real_name: nameRegExp }
      ];
    }
    
    // 地点模糊搜索
    if (phone && phone.trim()) {
      queryCondition.phone = db.RegExp({
        regexp: phone,
        options: 'i'
      });
    }

    // 创建基础查询
    const baseQuery = db.collection('users')
      .where(queryCondition)
      .field({
        _id: true,
        nickName: true,
        address: true,
        age: true,
        gender: true,
        real_name: true,
        hobby: true,
        phone: true,
        isDeleted:true,
      });

    // 并行获取总数和数据（保持高性能）
    const [countResult, res] = await Promise.all([
      baseQuery.count(),
      baseQuery.skip((page - 1) * pageSize)
               .limit(pageSize)
               .get()
    ]);
    return {
      code: 200,
      data: res.data,
      total: countResult.total,
      message: 'success'
    };
  } catch (error) {
    console.error('完整错误日志:', {
      error,
      queryParams: event // 记录查询参数
    });
    return {
      code: 500,
      message: `操作失败: ${error.errMsg || '未知错误'}`,
      errorDetail: error.message
    };
  }
};